package com.egg.basic.config.qiniu;

import com.egg.basic.util.FileQiniuUtil;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * 七牛配置
 */
@Profile({"prod", "test", "dev"})
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "file.qiniu")
public class QiniuConfig {


    // 私钥
    private String accessKey;
    // 公钥
    private String secretKey;
    // 储存空间
    private String bucket;
    // 外链域名
    private String domain;


    @Bean
    public Auth initAuth() {
        Auth auth;
        try {
            auth = Auth.create(getAccessKey(), getSecretKey());
            log.info("初始化成功 {}", Auth.class.getName());
            return auth;
        } catch (Exception e) {
            log.error("初始化失败 {} 原因 {}", Auth.class.getName(), e.getMessage());
        }
        return null;
    }

    @Bean
    public UploadManager initUploadManager() {
        UploadManager uploadManager;
        try {
            //构造一个带指定 Region 对象的配置类
            com.qiniu.storage.Configuration cfg = new com.qiniu.storage.Configuration(Region.region2());
            uploadManager = new UploadManager(cfg);
            log.info("初始化成功 {}", UploadManager.class.getName());
            return uploadManager;
        } catch (Exception e) {
            log.error("初始化失败 {} 原因 {}", UploadManager.class.getName(), e.getMessage());
        }
        return null;
    }

    /**
     * 装配
     *
     * @return
     */
    @Bean
    FileQiniuUtil initFileQiniuUtil(Auth auth, UploadManager uploadManager) {
        FileQiniuUtil fileQiniuUtil = new FileQiniuUtil();
        if (null == auth) {
            log.error("初始化失败 {} 原因 {}", FileQiniuUtil.class.getName(), Auth.class.getName() + "为null");
            return fileQiniuUtil;
        }
        if (null == uploadManager) {
            log.error("初始化失败 {} 原因 {}", FileQiniuUtil.class.getName(), UploadManager.class.getName() + "为null");
            return fileQiniuUtil;
        }
        fileQiniuUtil.setAuth(auth);
        fileQiniuUtil.setUploadManager(uploadManager);
        log.info("初始化成功 {}", FileQiniuUtil.class.getName());
        return fileQiniuUtil;
    }

}